(function (vc) {
    vc.extends({
        data: {
            editProductInfo: {
                shId: '',
                shName: '',
                productId: '',
                warnStock: '',
                categoryId: '',
                prodName: '',
                prodDesc: '',
                keyword: '',
                barCode: '1',
                unitName: '',
                sort: '',
                isPostage: '2',
                postage: '0.00',
                productCategorys: [],
                content: '',
                states: [],
                state: '',
                coverPhoto: '',
                carouselFigurePhoto: [],
                productSpecs: [],
                areaCode: '',
                distributionModes: [],
                housekeepingTypes: [],
                shopHouses: [],
                hktIds: []
            }
        },
        _initMethod: function () {
            $that._listEditProducts({
                productId: vc.getParam('productId')
            });
            $that._listProductH5Menu({
                productId: vc.getParam('productId')
            });
            
             $that._initEditProduct();
             $that._listShopHouses();
            vc.getDict('product', "state", function (_data) {
                $that.editProductInfo.states = _data;
            });
            $that._listEditHousekeepingTypes();
            $that._listEditProductCategorys();
        },
        _initEvent: function () {
            vc.on("editProduct", "notifyUploadCoverImage", function (_param) {
                if (_param.length > 0) {
                    $that.editProductInfo.coverPhoto = _param[0].url;
                } else {
                    $that.editProductInfo.coverPhoto = '';
                }
            });
            vc.on("editProduct", "notifyUploadCarouselFigureImage", function (_param) {
                $that.editProductInfo.carouselFigurePhoto = [];
                _param.forEach(_p => {
                    $that.editProductInfo.carouselFigurePhoto.push(_p.url);
                });
            });
        },
        methods: {
            editProductValidate() {
                return vc.validate.validate({
                    editProductInfo: $that.editProductInfo
                }, {
                    'editProductInfo.categoryId': [{
                        limit: "required",
                        param: "",
                        errInfo: "商品大类不能为空"
                    },
                    {
                        limit: "num",
                        param: "",
                        errInfo: "商品大类错误"
                    },
                    ],
                    'editProductInfo.prodName': [{
                        limit: "required",
                        param: "",
                        errInfo: "商品名称不能为空"
                    },
                    {
                        limit: "maxLength",
                        param: "128",
                        errInfo: "商品名称不能超过128位"
                    },
                    ],
                    'editProductInfo.prodDesc': [{
                        limit: "required",
                        param: "",
                        errInfo: "商品简介不能为空"
                    },
                    {
                        limit: "maxLength",
                        param: "256",
                        errInfo: "商品简介不能超过256位"
                    },
                    ],
                    'editProductInfo.keyword': [{
                        limit: "required",
                        param: "",
                        errInfo: "关键词不能为空"
                    },
                    {
                        limit: "maxLength",
                        param: "256",
                        errInfo: "关键词不能超过256位"
                    },
                    ],
                    'editProductInfo.barCode': [{
                        limit: "maxLength",
                        param: "15",
                        errInfo: "产品条码不能超过15位"
                    },],
                    'editProductInfo.shId': [{
                        limit: "required",
                        param: "",
                        errInfo: "仓库不能为空"
                    },],
                    'editProductInfo.unitName': [{
                        limit: "maxLength",
                        param: "32",
                        errInfo: "单位不能超过32位"
                    },],
                    'editProductInfo.sort': [{
                        limit: "num",
                        param: "",
                        errInfo: "排序格式错误"
                    },],
                    'editProductInfo.warnStock': [{
                        limit: "num",
                        param: "",
                        errInfo: "库存警告格式错误"
                    },],
                    'editProductInfo.isPostage': [{
                        limit: "num",
                        param: "",
                        errInfo: "是否包邮格式错误"
                    },],
                    'editProductInfo.postage': [{
                        limit: "money",
                        param: "",
                        errInfo: "邮费格式错误,请填写如 3.00"
                    },],
                });
            },
            _editProductInfo: function () {
                let hasDefault = false;
                if ($that.editProductInfo.productSpecs) {
                    $that.editProductInfo.productSpecs.forEach(item => {
                        if (item.isDefault != 'T' && item.isDefault != 'F') {
                            hasDefault = false;
                            return;
                        }
                        if (item.isDefault == 'T') {
                            hasDefault = true;
                        }
                    });
                }
                if (!hasDefault) {
                    vc.toast("未选择默认规格");
                    return;
                }
                if (!$that.editProductValidate()) {
                    vc.toast(vc.validate.errInfo);
                    return;
                }
                $that.editProductInfo.shopId = vc.getCurrentCommunity().shopId;
                $that.editProductInfo.areaCode = vc.getCurrentCommunity().areaCode;
                vc.http.apiPost(
                    '/product.updateProduct',
                    JSON.stringify($that.editProductInfo), {
                    emulateJSON: true
                },
                    function (json, res) {
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        let _json = JSON.parse(json);
                        if (_json.code == 0) {
                            //关闭model
                            vc.goBack();
                            vc.toast("修改成功");
                            return;
                        }
                        vc.toast(_json.msg);
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                        vc.toast(errInfo);
                    });
            },

            _closeEditProduct: function () {
                vc.goBack();
            },
            _listEditProductCategorys: function (_page, _rows) {
                let param = {
                    params: {
                        page: 1,
                        row: 50,
                        shopId: vc.getCurrentCommunity().shopId
                    }
                };
                //发送get请求
                vc.http.apiGet('/productCategory.queryProductCategory',
                    param,
                    function (json, res) {
                        let _json = JSON.parse(json);
                        $that.editProductInfo.productCategorys = _json.data;
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _initEditProduct: function () {
                let $summernote = $('.editSummernote').summernote({
                    lang: 'zh-CN',
                    height: 300,
                    placeholder: '必填，请输入商品描述',
                    callbacks: {
                        onImageUpload: function (files, editor, $editable) {
                            $that.sendEditFile($summernote, files);
                        },
                        onChange: function (contents, $editable) {
                            $that.editProductInfo.content = contents;
                        }
                    },
                    toolbar: [
                        ['style', ['style']],
                        ['font', ['bold', 'italic', 'underline', 'clear']],
                        ['fontname', ['fontname']],
                        ['color', ['color']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['height', ['height']],
                        ['table', ['table']],
                        ['insert', ['link', 'picture']],
                        ['view', ['fullscreen', 'codeview']],
                        ['help', ['help']]
                    ],
                });
            },
            sendEditFile: function ($summernote, files) {
                var param = new FormData();
                param.append("uploadFile", files[0]);
                param.append('shopId', vc.getCurrentCommunity().shopId);
                vc.http.upload('/upload/uploadFile',
                    param, {
                    emulateJSON: true,
                    //添加请求头
                    headers: {
                        "Content-Type": "multipart/form-data"
                    }
                },
                    function (json, res) {
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        if (res.status == 200) {
                            var data = JSON.parse(json);
                            //关闭model
                            $summernote.summernote('insertImage', data.data.url);
                            return;
                        }
                        vc.toast(json);
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                        vc.toast(errInfo);
                    });
            },
            _openEditChooseSpecModal: function () {
                let _productSpec = {
                    specCd: "0",
                    stock: "0",
                    sales: "0",
                    price: "0.00",
                    costPrice: "0.00",
                    ownerPrice: "0.00",
                    vipPrice: "0.00",
                    otPrice: "0.00",
                    deduction: "0.00",
                    isDefault: "F",
                    barCode: ""
                }
                $that.editProductInfo.productSpecs.push(_productSpec);
                let _productSpecs = $that.editProductInfo.productSpecs;
                let flag = false;
                for (let i = 0; i < _productSpecs.length; i++) {
                    if (_productSpecs[i].isDefault == "T") {
                        flag = true;
                        break;
                    }
                }
                if (!flag && _productSpecs.length > 0) {
                    _productSpecs[0].isDefault = "T"
                }
            },
            _openEditDeleteProductSpec: function (_productSpec) {
                let _productSpecs = $that.editProductInfo.productSpecs;
                let index = 0;
                if (_productSpecs != null && _productSpecs != 'undefined' && _productSpecs != '') {
                    index = _productSpecs.indexOf(_productSpec);
                }
                if (index > -1) {
                    _productSpecs.splice(index, 1);
                }
                let flag = false;
                for (let i = 0; i < _productSpecs.length; i++) {
                    if (_productSpecs[i].isDefault == "T") {
                        flag = true;
                        break;
                    }
                }
                if (!flag && _productSpecs.length > 0) {
                    _productSpecs[0].isDefault = "T"
                }
            },
            _editDistributionModes: function () {
                var param = {
                    params: {
                        page: 1,
                        row: 50,
                        shopId: vc.getCurrentCommunity().shopId
                    }
                };
                //发送get请求
                vc.http.apiGet('/distributionMode/queryDistributionMode',
                    param,
                    function (json, res) {
                        var _distributionModeManageInfo = JSON.parse(json);
                        $that.editProductInfo.distributionModes = _distributionModeManageInfo.data;
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _listEditProducts: function (_product) {
                var param = {
                    params: {
                        page: 1,
                        row: 1,
                        productId: _product.productId
                    }
                };
                //发送get请求
                vc.http.apiGet('/product.queryProduct',
                    param,
                    function (json, res) {
                        var _productManageInfo = JSON.parse(json);
                        let product = _productManageInfo.data[0];
                        vc.copyObject(product, $that.editProductInfo);
                        let _photos = [];
                        _photos.push(product.coverPhoto);
                        vc.emit('editProductCover', 'uploadImageUrl', 'notifyPhotos', _photos);
                        vc.emit('editProductCarouselFigure', 'uploadImageUrl', 'notifyPhotos', product.carouselFigurePhotos);
                        $(".editSummernote").summernote('code', product.content);
                        let _productSpecValues = product.productSpecValues;
                        if (_productSpecValues) {
                            _productSpecValues.forEach(item => {
                                let _productSpecDetails = item.productSpecDetails;
                                let _specValue = '';
                                if (_productSpecDetails) {
                                    _productSpecDetails.forEach(detail => {
                                        _specValue += (detail.detailValue + "/");
                                    });
                                }
                                item.specValue = _specValue;
                            });
                        }
                        $that.editProductInfo.productSpecs = _productSpecValues;
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _doEditDefaultProductSpec: function (_product, _defaultProductSpec) {
                if (_product.productSpecs != null && _product.productSpecs != 'undefined' && _product.productSpecs != '') {
                    _product.productSpecs.forEach(item => {
                        item.isDefault = "F";
                    });
                }
                _defaultProductSpec.isDefault = "T";
                $that.editProductInfo.editProductInfo = JSON.parse(JSON.stringify(_product.productSpecs));
            },
            _changeShopHouse: function (_shopHouseId) {
                if ($that.productManageInfo.shopHouses != null && $that.productManageInfo.shopHouses != 'undefined' && $that.productManageInfo.shopHouses != '') {
                    $that.productManageInfo.shopHouses.forEach(item => {
                        if (item.shId == _shopHouseId) {
                            $that.editProductInfo.shName = item.shName;
                        }
                    });
                }
            },
            _listEditHousekeepingTypes: function (_page, _rows) {
                let param = {
                    params: {
                        page: 1,
                        row: 30,
                        typeCd: '2002',
                        shopId: '9999',
                        skipType: '3'
                    }
                };
                //发送get请求
                vc.http.apiGet('/housekeepingType.queryHousekeepingType',
                    param,
                    function (json, res) {
                        let _housekeepingTypeManageInfo = JSON.parse(json);
                        $that.editProductInfo.housekeepingTypes = _housekeepingTypeManageInfo.data;

                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _listProductH5Menu: function (_product) {
                $that.editProductInfo.hktIds = [];
                let param = {
                    params: {
                        page: 1,
                        row: 30,
                        productId: _product.productId
                    }
                };
                //发送get请求
                vc.http.apiGet('/productH5Menu.listProductH5Menu',
                    param,
                    function (json, res) {
                        let _datas = JSON.parse(json).data;
                        _datas.forEach(item => {
                            $that.editProductInfo.hktIds.push(item.hktId)
                        })
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _listShopHouses: function (_page, _rows) {
                let param = {
                    params: {
                        page: 1,
                        row: 100,
                        shopId: vc.getCurrentCommunity().shopId
                    }
                };
                //发送get请求
                vc.http.apiGet('/shopHouse.queryShopHouse',
                    param,
                    function (json, res) {
                        let _json = JSON.parse(json);
                        $that.editProductInfo.shopHouses = _json.data;
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
        }
    });
})
    (window.vc);